﻿using Infragistics.WebUI.UltraWebGrid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Configuration;
using CamstarAPI;

public partial class Custom_BwPlanManager_BwContainerBatchStartPopupForm : BaseForm
{
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    uMESCommonBusiness commonBal = new uMESCommonBusiness();

    string businessName = "批次管理", parentName = "Container";
    protected void Page_Load(object sender, EventArgs e)
    {
        lStatusMessage.Text = "";
        getProductInfo.GetProductData += new GetProductInfo_ascx.GetProductDataEventHandler(LoadProductData);
        getWorkFlowInfo.GetWorkFlowData += new GetWorkFlowInfo_ascx.GetWorkFlowDataEventHandler(LoadWorkflowData);
        getProductInfo.DDlProductDataChanged += new GetProductInfo_ascx.DDlProductDataChangedEventHandler(DDlProductDataChanged);


        if (IsPostBack == false)
        {
            DataTable dt = PopupData as DataTable;
            Session.Remove("PopupData");

            containerBal.dealPopupDt(ref dt);
            dt.Columns.Add("ConPlannedStartDate"); dt.Columns.Add("ConPlannedCompletionDate");
            foreach (DataRow row in dt.Rows)
            {
                row["ConPlannedStartDate"] = DateTime.Now.ToString("yyyy-MM-dd");
                    row["ConPlannedCompletionDate"]=row["PlannedCompletionDate"];
            }

            gdMfgorder.DataSource = dt;
            gdMfgorder.DataBind();
            
        }
    }

    #region 事件
    protected void gdMfgorder_ActiveRowChange(object sender, Infragistics.WebUI.UltraWebGrid.RowEventArgs e)
    {
        ActiveRow(e.Row);
    }
    //调整
    protected void btnAdjust_Click(object sender, EventArgs e)
    {
        Adjust();
    }

    protected void CloseButton_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> returnToMain = new Dictionary<string, string>();

        returnToMain["Page"] = "BwContainerBatchStartPopupForm.aspx";
        PopupData = returnToMain;
        ClosePopupPage(false);
        // ClientScript.RegisterStartupScript(this.GetType(), "NotifyParent", "<script> window.returnValue = true; window.close();</script> ");
    }
    
    protected void btnStart_Click(object sender, EventArgs e)
    {
        try {
            ResultModel result = ContainersStart();
            DisplayMessage(lStatusMessage, result.Message, result.IsSuccess);

            if (result.IsSuccess) {
                //批次开卡完成，增加记录
                List<ContainerStartModel> containers = result.Data as List<ContainerStartModel>;
                List<MESAuditLog> entitys = new List<MESAuditLog>();
                MESAuditLog ml = new MESAuditLog();
                foreach (ContainerStartModel con in containers) {

                    var temp = containerBal.GetTableInfo("Container", "ContainerName", con.ContainerName);
                    if (temp.Rows.Count == 0) {
                        continue;
                    }

                    ml = new MESAuditLog();

                    ml.ContainerName = con.ContainerName; ml.ContainerID = temp.Rows[0]["ContainerID"].ToString();
                    ml.ParentID = temp.Rows[0]["ContainerID"].ToString(); ml.ParentName = parentName;
                    ml.CreateEmployeeID = UserInfo["EmployeeID"];
                    ml.BusinessName = businessName; ml.OperationType = 0;
                    ml.Description = "批次创建:" + ml.ContainerName + "创建成功,数量:"+ temp.Rows[0]["Qty"].ToString();

                    entitys.Add(ml);
                }
                commonBal.SaveMESAuditLogs(entitys);
                //
                Dictionary<string, string> returnToMain = new Dictionary<string, string>();

                returnToMain["Page"] = "BwContainerBatchStartPopupForm.aspx";
                returnToMain["Message"] = "批量创建成功";

                PopupData = returnToMain;

                ClosePopupPage(true);
            }

        } catch (Exception ex) {
            DisplayMessage(lStatusMessage, ex.Message, false);
        }
    }
        #endregion

        #region 方法
        void LoadProductData()
    {
        if (getProductInfo.Message.Length > 0)
        {
            DisplayMessage(lStatusMessage, getProductInfo.Message, false);
        }
    }

    void LoadWorkflowData()
    {
        if (getWorkFlowInfo.Message.Length > 0)
        {
            DisplayMessage(lStatusMessage, getWorkFlowInfo.Message, false);
        }
    }
    /// <summary>
    /// 件号更改带出工艺
    /// </summary>
    void DDlProductDataChanged()
    {
        getWorkFlowInfo.InitControl();
        
        string productName = "";

        string productRev = "";

        GetProductInfo(ref productName,ref productRev);

        if (productName == "")
        {
            return;
        }

        Dictionary<string, string> para = new Dictionary<string, string>();
        para["ProductName"] = productName;
        para["ProductRev"] = productRev;

        getWorkFlowInfo.SearchWorkFlow(para, 1);

    }

    //点击行
    void ActiveRow(UltraGridRow activeRow) {
        getProductInfo.InitControl();
        getWorkFlowInfo.InitControl();
        txtContainerYearNo.Text = "";
        txtContainerNo.Text = "";
        txtPlannedstartdate.Value = "";
        txtPlannedcompletiondate.Value = "";
        //加载产品
        string productName = activeRow.Cells.FromKey("ProductName").Text;
        string productId= activeRow.Cells.FromKey("ProductID").Text;
        getProductInfo.GetProductNameOrTypeText.Text = productName;
        getProductInfo.DoSearchProductInfo();
        getProductInfo.GetProductDDL.SelectedValue = productId;
        //加载默认工艺
        DDlProductDataChanged();
        //批次号
        string containerNo = activeRow.Cells.FromKey("ContainerNo").Text;

        txtContainerYearNo.Text = containerNo.Substring(0, 2);
        txtContainerNo.Text = containerNo.Substring(2);

        txtQty.Text= activeRow.Cells.FromKey("Qty").Text;

    }

    //获取产品名及版本
    void GetProductInfo(ref string productName,ref string productRev) {
        string productInfo = getProductInfo.ProducText;
        if (string.IsNullOrWhiteSpace(productInfo)) {
            return;
        }
         productName = productInfo.Substring(0, productInfo.IndexOf(":"));
      
            productRev = productInfo.Substring(productInfo.IndexOf(":") + 1, productInfo.IndexOf("(", productName.Length) - productInfo.IndexOf(":") - 1);
        
    }

    //获取工艺名及版本
    void GetWorkflowInfo(ref string workflowName, ref string workflowRev)
    {
        string strWrokflow = getWorkFlowInfo.WorkFlowText;

        if (string.IsNullOrWhiteSpace(strWrokflow))
        {
            return;
        }

        workflowName = getWorkFlowInfo.WorkFlowText.Substring(0, strWrokflow.IndexOf(":"));
       
            workflowRev = strWrokflow.Replace(workflowName+":", "");

    }

    //调整
    void Adjust() {
        var activeRow = gdMfgorder.DisplayLayout.ActiveRow;

        if (activeRow == null)
        {
            DisplayMessage(lStatusMessage,"请先选择行",false);
            return;
        }

        if (string.IsNullOrWhiteSpace(txtContainerNo.Text))
        {
            DisplayMessage(lStatusMessage, "批次号不能为空", false);
            return;
        }

        if (string.IsNullOrWhiteSpace(txtQty.Text))
        {
            DisplayMessage(lStatusMessage, "数量", false);
            return;
        }

        if (!string.IsNullOrWhiteSpace(txtPlannedstartdate.Value) || !string.IsNullOrWhiteSpace(txtPlannedcompletiondate.Value))
        {
            if (string.IsNullOrWhiteSpace(txtPlannedstartdate.Value) || string.IsNullOrWhiteSpace(txtPlannedcompletiondate.Value))
            {
                DisplayMessage(lStatusMessage, "批次的计划开始和完成时间需同时存在", false);
                return;
            }

            DateTime startDate, finishDate;
            if (!DateTime.TryParse(txtPlannedstartdate.Value, out startDate) || !DateTime.TryParse(txtPlannedcompletiondate.Value, out finishDate))
            {
                DisplayMessage(lStatusMessage, "时间格式错误", false);
                return;
            }
            if (startDate > finishDate)
            {
                DisplayMessage(lStatusMessage, "批次的计划开始时间不能大于计划完成时间", false);
                return;
            }
        }

        string productName="", productRev="", workflowName="", workflowRev="";
        GetProductInfo(ref productName,ref productRev); GetWorkflowInfo(ref workflowName,ref workflowRev);

        activeRow.Cells.FromKey("ProductName").Value = productName;
        activeRow.Cells.FromKey("ProductRev").Value = productRev;
        activeRow.Cells.FromKey("ProductID").Value = getProductInfo.ProductValue;
        activeRow.Cells.FromKey("Product").Value = productName+":"+productRev;

        string productDesc = "";
        DataTable tempDt = containerBal.GetTableInfo("product", "productid", getProductInfo.ProductValue);
        if (tempDt.Rows.Count > 0)
        {
            productDesc = tempDt.Rows[0]["description"].ToString();
        }
        activeRow.Cells.FromKey("ProductDesc").Value = productDesc;

        activeRow.Cells.FromKey("WorkflowName").Value = workflowName;
        activeRow.Cells.FromKey("WorkflowRev").Value = workflowRev;
        activeRow.Cells.FromKey("WorkflowID").Value = getWorkFlowInfo.WorkFlowValue;
        activeRow.Cells.FromKey("Workflow").Value = workflowName + ":" + workflowRev;

        
        string containerNo = txtContainerYearNo.Text + txtContainerNo.Text;
        activeRow.Cells.FromKey("ContainerNo").Value = containerNo;

        activeRow.Cells.FromKey("Qty").Value = txtQty.Text;

        activeRow.Cells.FromKey("ConPlannedStartDate").Value = txtPlannedstartdate.Value;
        activeRow.Cells.FromKey("ConPlannedCompletionDate").Value = txtPlannedcompletiondate.Value;

    }

    /// <summary>
    /// 批量开卡
    /// </summary>
    /// <returns></returns>
    ResultModel ContainersStart() {
        ResultModel result = new ResultModel(false, "");

        List<ContainerStartModel> containers = new List<ContainerStartModel>();

        string startReason = ConfigurationManager.AppSettings["DefaultStartReason"];
        string level = ConfigurationManager.AppSettings["DefaultContainerLevel"];
        string owner = ConfigurationManager.AppSettings["DefaultOwner"];

        foreach (UltraGridRow row in gdMfgorder.Rows)
        {
            ContainerStartModel container = new ContainerStartModel();
            container.StartReason = startReason;
            container.Level = level;
            container.Owner = owner;

            container.ContainerName = row.Cells.FromKey("ProductName").Text + "/" + row.Cells.FromKey("ContainerNo").Text;
            container.ProductName = row.Cells.FromKey("ProductName").Text;
            container .ProductRev = row.Cells.FromKey("ProductRev").Text;
            container.Qty=int.Parse( row.Cells.FromKey("Qty").Text);
            container.Mfgorder = row.Cells.FromKey("MfgorderName").Text;
            container.PlannedStartDate = row.Cells.FromKey("ConPlannedStartDate").Text;
            container.PlannedCompletionDate = row.Cells.FromKey("ConPlannedCompletionDate").Text;
            container.StartEmployee = UserInfo["EmployeeName"];
            container.WorkflowName = row.Cells.FromKey("WorkflowName").Text;
            container.WorkflowRev = row.Cells.FromKey("WorkflowRev").Text;

            //批次属性
            if (!string.IsNullOrWhiteSpace(row.Cells.FromKey("ReplaceMaterial").Text) && !string.IsNullOrWhiteSpace(row.Cells.FromKey("ReplaceMaterialName").Text)
                && !string.IsNullOrWhiteSpace(row.Cells.FromKey("ReplaceMaterialQty").Text))
            {
                DataTable attributeList = new DataTable();
                attributeList.Columns.Add("Name"); attributeList.Columns.Add("Value");

                DataRow attributeRow = attributeList.NewRow();
                attributeRow["Name"] = "代料规格型号";
                attributeRow["Value"] = row.Cells.FromKey("ReplaceMaterial").Text;
                attributeList.Rows.Add(attributeRow);

                attributeRow = attributeList.NewRow();
                attributeRow["Name"] = "代料名称";
                attributeRow["Value"] = row.Cells.FromKey("ReplaceMaterialName").Text;
                attributeList.Rows.Add(attributeRow);

                float qty = 0; float mfgQty = float.Parse(row.Cells.FromKey("MfgQty").Text);//MfgQty
                qty = container.Qty * float.Parse(row.Cells.FromKey("ReplaceMaterialQty").Text) / mfgQty;
                attributeRow = attributeList.NewRow();
                attributeRow["Name"] = "代料数";
                attributeRow["Value"] = qty;
                attributeList.Rows.Add(attributeRow);

                container.AttributeList = attributeList;
            }

            containers.Add(container);

            if (string.IsNullOrWhiteSpace(container.WorkflowName)) {
                return new ResultModel(false, "有空工艺");
            }
            if (container.Qty<=0)
            {
                return new ResultModel(false, "数量必须大于0");
            }
         }

        CamstarClientAPI api = new CamstarClientAPI(UserInfo["ApiEmployeeName"], UserInfo["ApiPassword"]);

        string strInfo="";
        result.IsSuccess = api.ContainerStarts(containers, ref strInfo);
        result.Message = strInfo;
        result.Data = containers;
        return result;



    }
    #endregion





}